import { defineStore } from 'pinia'

const useUserStore = defineStore("user", {
  state: () => ({
    userinfo:{},
    token: "",
    tasklist: [],
    selectDay: '',
    today: '',
  }),

  getters: {


    getSelectedDay: state => state.selectDay,

    getTodayTodoList: state => state.tasklist.filter(function (item) {
      console.log(item.timestamp)
      return item.timestamp == state.today
    }),



    getTodayDate: state => state.today,

    computedStatusPercents: state => {
      const { tasklist } = state
      console.log(tasklist)
      const total = tasklist.length
      const { failedEvents, completedEvents } = tasklist.reduce((acc, item) => {
        if (item.status === 'doing') {
          acc.failedEvents++
        } else if (item.status === 'finished') {
          acc.completedEvents++
        }
        return acc
      }, { failedEvents: 0, completedEvents: 0 })
    
      
      const failedPercent = (failedEvents / total) * 100
      const completedPercent = (completedEvents / total) * 100

      console.log(failedPercent,completedEvents)
      return [Math.round(failedPercent), Math.round(completedPercent)]
    },
    

    getSelectedDateList: state => {
      const { tasklist, selectDay } = state
      return tasklist.filter(item => item.timestamp === selectDay)
    }
    
  },

  actions: {

    setUserInfo(val){
      this.userinfo = val
    },

    setSelectDay(val) {
      this.selectDay = val

    },

    setToday(val) {
      this.today = val.date

    },

    clearToken() {
      this.token = ''
    },
    
    getTaskList(){
      return this.tasklist
    },

    setAccessToken(val) {
      this.token = val
    },



    finishedTask(id){
      const index = this.tasklist.findIndex(item => item._id === id)
      if (index !== -1) {
        this.$set(this.tasklist[index], 'status', 'finished')
      }
      
    },
    insertTask(task) {
      this.tasklist.unshift(task)
    },
    updateTaskList(tasklist) {
      this.tasklist = tasklist
    },

    updateTask(task,id){
      const index = this.tasklist.findIndex(item => item._id === id)
      if (index !== -1) {
        Object.assign(this.tasklist[index], task)
      }
    }

  },

 


  persist: {
    enabled: true
  }


})

export default useUserStore